home *** CD-ROM | disk | FTP | other *** search
- Path: news.nevada.edu!not-for-mail
- From: chancl@nevada.edu (Clapton Chan)
- Newsgroups: comp.lang.c
- Subject: Re: How to get a random string each time??
- Date: 17 Feb 1996 10:54:46 GMT
- Organization: University of Nevada System Computing Services
- Message-ID: <4g4c5m$tlb@news.nevada.edu>
- References: <4fh5od$qq0@news.nevada.edu>
- NNTP-Posting-Host: unauthenticated_user@pioneer.nevada.edu
- X-Newsreader: TIN [UNIX 1.3 950520BETA PL0]
-
- Thanks for all of you kind C gurus. My problem is solved.
- I did make some stupid code earlier, but hey, everyone gives
- the new guy a break, right?
-
- I now post my solution for your comments.
-
- **************Here*is*the*question*********************
-
- Write a program that reads the list of strings and then selects
- and prints a random string from the list.
-
- *************Here*is*my*solution***********************
-
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h> /* This is where srand and rand is located.*/
-
- int main ()
- {
- char *p, str[10][80];
- int i, j;
-
- srand(time(NULL)); /* pseudocode */
- printf("Enter 10 strings (or '999' to quit):\n");
- for(i=0; i<10; i++) {
- fgets(str[i], sizeof(str[i]), stdin);
- if((p=strchr(str[i], '\n')) != NULL) *p='\0';
- if(!(strcmp(str[i], "999")))
- break;
- }
-
- j = rand();
- j = j%i; /* this handles early program exit */
- printf("\nAnswer: %s\n", str[j]);
-
- return 1;
- }
-
- *************************End******************************
-
- I hope this program is bug-less. ;)
-
- Cheers,
- Clapton
- http://www.nevada.edu/home/15/chancl/html/homepage.html
-